package cn.xz.tipsum.dialog

import android.util.Log
import android.view.Gravity
import android.widget.SeekBar
import android.widget.TextView
import android.widget.Toast
import cn.xz.tipsum.R
import cn.xz.tipsum.base.BaseApplication
import cn.xz.tipsum.base.BaseDialogRxFragment
import cn.xz.tipsum.utils.DownloadUtil
import java.io.File


/**
 * 加载弹窗
 * */
class LoadingDialog: BaseDialogRxFragment() {

    private var type = "W"
    private var url = "http://www.hualao.icu/wx.apk"
    private var name = "微信.apk"
    private var sb: SeekBar? = null
    private var tvLoading: TextView? = null
    private var tvSure: TextView? = null

    companion object {
        fun newInstance(type: String): LoadingDialog {
            val mDialog = LoadingDialog()
            mDialog.type = type
            return mDialog
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.dialog_loading
    }

    override fun configDialog() {
        this.setDialogSize(gravity = Gravity.CENTER,width = 380)
    }

    override fun initViews() {
        dialog?.let {
            sb = it.findViewById(R.id.sb)
            tvSure = it.findViewById(R.id.tv_sure)
            tvLoading = it.findViewById(R.id.tv_loading)
        }

        tvSure?.text =  "${if (type == "W") "微信" else "支付宝"}下载中,请耐心等待..."
        url = if (type == "W") "http://www.hualao.icu/wx.apk" else "http://www.hualao.icu/zfb.apk"
        name = if (type == "W") "微信安装包.apk" else "支付宝安装包.apk"
        //点击外部不隐藏
        dialog?.setCancelable(false)
        dialog?.setCanceledOnTouchOutside(false)
        //视图
        initUI()
    }

    private fun initUI(){
        DownloadUtil.download(url,
            DownloadUtil.getUrlPath(),name,object : DownloadUtil.OnDownloadListener{
            override fun onDownloadSuccess(file: File?) {
                //更新视频到相册
                Log.e("视频下载", "下载成功: ${file?.absolutePath}")
                dismiss()
            }
            override fun onDownloading(progress: Int) {
                Log.e("视频下载", "下载进度:${progress}")
                sb?.post {
                   sb?.progress = progress
                    tvLoading?.text = "${progress}%"
                }
            }

            override fun onDownloadFailed(e: Exception?) {
                Log.e("视频下载", "下载失败:${e?.printStackTrace()}")
                Toast.makeText(BaseApplication.getContext(),"下载失败,请稍后重试~", Toast.LENGTH_LONG).show()
                dismiss()
            }

        })

    }

}